package org.net.cms.controller.app.parentccount;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.net.cms.config.Result;
import org.net.cms.controller.app.parentccount.vo.AppUpdatePasswordReqVO;
import org.net.cms.service.parentaccount.ParentAccountService;
import org.net.cms.uitl.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/app/account")
@Tag(name = "APP - 家长账号管理")
public class AppParentAccountController {
    // 接口测试无误

    @Resource
    private ParentAccountService parentAccountService;

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/check")
    @Operation(summary = "登录验证")
    public Result login(@RequestParam String phone, @RequestParam String password) {
        try {
            JwtUtil jwtUtil = new JwtUtil();
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(phone, password);
            Authentication authentication = authenticationManager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return Result.success(jwtUtil.getToken(userDetails.getUsername()));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("账号或密码错误！");
        }
    }

    // 增加家长可以修改密码接口
    @PostMapping("/update")
    @Operation(summary = "修改密码")
    public Result updatePassword(@RequestBody AppUpdatePasswordReqVO updatePasswordReqVO) {
        if (parentAccountService.updatePassword(updatePasswordReqVO)) {
            return Result.success("修改成功!");
        }
        return Result.error("旧密码不正确！");
    }

    // 家长解绑某个孩子（需要后台同意）
    @PostMapping("/unbind")
    @Operation(summary = "解绑某个学生")
    public Result unbindStudent(@RequestParam int studentId) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String phone = userDetails.getUsername();
        if (parentAccountService.submitUnbindStudent(phone, studentId)) {
            return Result.success();
        }
        return Result.error("已存在解绑申请，请等待审核！");
    }
}
